package com.zxy.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;

import java.util.Calendar;
import java.util.Map;

public class JWTUtils {
    /**
     * 生成header payload signnature
     */
    private static final String SIGN = "!HDHIQKBFAIN";

    /**
     * 生成token
     *
     * @param map 存储用户信息
     * @return 返回token
     */
    public static String getToken(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 1); // 默认1天过期
        JWTCreator.Builder builder = JWT.create();
        // payload  两种写法均可
        /*map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });*/
        map.forEach(builder::withClaim);
        // 指定过期时间
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(SIGN));
    }

    /**
     * 验证token
     *
     * @param token 接收token
     */
    public static void verify(String token) {
        try {
            JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        } catch (JWTVerificationException e) {
            throw new JWTVerificationException("JWT验证异常");
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("参数不合法");
        }
    }
}
